package Server;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

/**
 * <p>Title: CGIHandler.java</p>
 *
 * <p>Description: Used to handle cgi script requests. It will create a runnable
 * thread which will execute the script on the server and read the output from
 * that script, which will then be sent back to the client.</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 * @author Luping May and Tracie Hong
 * @version 1.0
 */
public class CGIHandler {

    /**
     * Constructor for CGIHandler class. Used to save the variables necessary for
     * the cgi script to run properly and for the response to be sent back to the
     * client.
     *
     * @param rq Request variable which correlates to the request that was sent
     *   from the client to the server.
     * @param ev Environment variable used to get the state of the server
     *   environment. This information should have been saved when the server was
     *   configured.
     */
    public CGIHandler(Request rq, Environment ev) {
        _request = rq;
        _environment = ev;
    }

    /**
     * Function used to execute the cgi script that was being requested by the
     * client. 
     * 
     * HINT: Try using the Runtime.getRuntime().exec() function to execute
     * the script. Also look into using both Data and Buffered Streams.
     *
     * @return BufferedInputStream which is the output from the script execution.
     *   This is sent back to the server and then back to the client.
     * @throws Exception 
     */
    public BufferedInputStream runScript(String path) throws Exception {
        BufferedInputStream in = null;
        File file = new File(path);
        String perlExePath = null;
        if (file.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                perlExePath = br.readLine().replace("#!", ""); //perl in system
                perlExePath = perlExePath.replace("\"", "");
            } catch (IOException e) {
                System.out.println("Error opening file");
                System.exit(1);
            }
        }
        String scriptName = path.substring(path.lastIndexOf("/") + 1);
        String directoryName = path.substring(0, path.lastIndexOf("/"));
        if (perlExePath != null) {
            ProcessBuilder pb = new ProcessBuilder(perlExePath, scriptName, _request.getQuery());

            Map<String, String> env = pb.environment();
            _environment.setEnv(env);
            _environment.addEnvVar("SCRIPT_NAME", scriptName);

            pb.directory(new File(directoryName));
            Process p = null;
            try {
                p = pb.start();
                if (_request.getMethod().equals("POST")) {
                    BufferedOutputStream stdin = new BufferedOutputStream(p.getOutputStream());
                    stdin.write(_request.getBody());
                    stdin.flush();
                }
                in = new BufferedInputStream(p.getInputStream());
            } catch (IOException ex) {
                throw new Exception("Error processing request.");
            }
        }
        return in;
    }
    private Request _request;
    private Environment _environment;
}

